<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>
<style>
    .equipment-container {
        display: flex;
        align-items: center;
    }

    .equipment:before {
        content: url(../image/equipment.png);
    }

    .alarm:before {
        content: url(../image/alarm.png);
    }

    .knowledge:before {
        content: url(../image/knowledge.png);
    }

    .photoadd:before {
        content: url(../image/photo-add.png);
    }

    .equipment {
        display: inline-block;
        margin-top: 4px;
    }


    .alarm {
        display: inline-block;
        margin-top: 4px;
    }

    .equipment-container h3 {
        font-weight: bold;
        margin: 0 0 0 8px;
        display: inline-block;
    }



    .knowledge {
        display: inline-block;
        margin-top: 4px;
    }
</style>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            设备故障提报
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;">
        <div class="equipment-container">
            <span class="equipment"></span>
            <h3>设备信息</h3>
            <div style="float:right;margin:0 15px 0 auto;display: flex;align-items: center;" tapmode id="scan"
                onclick="doScan()">
                <i class="aui-iconfont aui-icon-scan" style="font-size: 1.2rem;"></i>
                <span style="margin-left: 5px;">扫设备码添加</span>
            </div>

        </div>
        <ul class="aui-list aui-form-list">
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">设备编码<span style="color:red">*</span></div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="请选择设备" id="equipCode" value="" onclick="toNewPage()" />
                    </div>
                    <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="toNewPage()"></i>
                </div>
            </li>
        </ul>
        <div class="equipment-container">
            <span class="alarm"></span>
            <h3>故障信息</h3>
            <div style="float:right;margin:0 15px 0 auto;display: flex;align-items: center;" onclick="toNewPage2()">
                <i class="knowledge"></i>
                <span style="color: #1296db;margin-left: 5px;">经验库</span>
            </div>
        </div>
        <div style="background-color: white;padding-bottom: 1%;">
            <h3>故障描述</h3>
            <textarea rows="3" placeholder="输入故障描述" id="description"
                style="width: 96%;background-color: #F0F1F4;margin:0 2%;"></textarea>
        </div>

        <ul class="aui-list aui-form-list">
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">报修语音</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="点击录音" id="voice">
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">添加图片</div>
                    <div class="aui-list-item-input">
                        <div class="aui-content" style="background-color: #ffffff">
                            <ul class="aui-list-view aui-grid-view" id="imgslist">
                                <li class="aui-list-view-cell aui-img aui-col-xs-4 aui-padded-5" id="addpic"
                                    onclick="imgClick()">
                                    <img class="aui-img-object" style="padding: 5px;" src="../image/photo-add.png">
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </li>

            <li class="aui-list-item">
                <div class="aui-list-item-label">是否停机</div>
                <div class="aui-list-item-inner" style="display: flex; align-items: center;">
                    <div style="display: flex; align-items: center;">
                        <input class='aui-radio' type='radio' value="是" name='isStop' checked>
                        <div class='aui-checkbox-name' style="margin: 0 25px 0 5px;">是</div>
                        <input class='aui-radio' type='radio' value="否" name='isStop'>
                        <div class='aui-checkbox-name' style="margin: 0 5px;">否</div>
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">设备位置</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="请输入设备位置" id="location" value="" />
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">发生时间</div>
                    <div class="aui-list-item-input">
                        <input type="text" id="happen" onclick="showTime();">
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">报修人</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="请输入报修人" id="bxPerson" value="" />
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">联系方式</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="请输入联系方式" id="mobile">
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">紧急程度</div>
                    <select id="urgent">
                        <option value=''>--请选择--</option>
                        <option value='紧急'>紧急</option>
                        <option value='高'>高</option>
                        <option value='中'>中</option>
                        <option value='低'>低</option>
                    </select>
                </div>
            </li>

        </ul>
        <div style="width:100%;margin-top:2%;"></div>
        <div class="aui-btn aui-btn-info aui-btn-block" onclick="save()">提交</div>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/hammer.min.js"></script>
<script type="text/javascript">
    //光标所在id
    var idSelector = "";
    var equipId = "";//设备ID
    var personCode = "";

    var uiMediaScanner = null;
    var imageFilter = null;
    var imageBrowser = null;

    //初始化
    apiready = function () {

        $("#equipCode").focus();
        idSelector = "equipCode";
        // $("#isUrgent").val("否");
        //查询维修类型下拉框
        // getEquipFaultCombox();

        // 引入多选模块
        uiMediaScanner = api.require('UIMediaScanner');
        // 引入过滤压缩模块
        imageFilter = api.require("imageFilter");
        // 引入图片浏览模块
        imageBrowser = api.require('imageBrowser');
        crateDate()

        getUserName()
    }

    // 获取光标所在组件的id
    function getIdSelector() {
        var e = event || window.event;
        var el = e.srcElement || e.target;
        idSelector = el.id;
        $("#" + el.id).select();
    }

    // 获取当前日期和时间（包含时分秒）
    function crateDate() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();

        // 新增时分秒的获取和补零处理
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

        // 格式化为 "年-月-日 时:分:秒"
        $("#happen").val(year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds);
    }
    function showTime() {
        var moduleTimer = api.require('moduleTimer');
        moduleTimer.showTimer({
            startTime: '2000-01-1 00:00',//可选择的起始时间
            endTime: '2099-12-31 23:59',//可选择的结束时间
            timeFormat: 'yyyy-MM-dd HH:mm:ss',//返回的时间格式，如果不传默认是yyyy-MM-dd HH:mm:ss
            selColor: '#079962'//选中的颜色值
        }, function (ret, err) {
            var finishDate = ret;
            var text = document.getElementById("happen");
            text.value = finishDate;
        });
    }

    function getUserName() {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getUserNameInfo";
        var data = {
            values: {
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //返回成功
                if (myobj.code == "0") {
                    var list = eval(myobj.list);
                    var html = "";
                    if (list && list.length > 0) {

                        $("#bxPerson").val(list[0].name);
                        $("#mobile").val(list[0].mobile);
                    }
                }
            }
        });
    }

    //报废记录保存
    function save() {
        var equipCode = $("#equipCode").val();
        //设备编码非空校验
        if (equipCode == null || equipCode == "" || equipCode == undefined) {
            api.toast({
                msg: "请 选择/扫描 设备编码!",
                duration: 3000
            });
            return;
        }

        doSave()
    }
    function doSave() {
        const checkedRadio = Array.from(document.getElementsByName('isStop')).find(radio => radio.checked);
    
        // 2. 判断是否找到选中按钮（避免无选中时报错）
        var isStop = checkedRadio ? checkedRadio.value : '';

        //设备编码
        var equipCode = $("#equipCode").val();
        //故障描述
        var description = $("#description").val();
        var voice = $("#voice").val();
        // var isStop = $("#isStop").val();
        var location = $("#location").val();
        var happen = $("#happen").val();
        var bxPerson = $("#bxPerson").val();
        var mobile = $("#mobile").val();
        var urgent = $("#urgent").val();

        if (equipCode == undefined || equipCode == null || equipCode == '') {
            api.toast({
                msg: "设备编码不允许为空！",
                duration: 3000
            });
            return
        }
        if (description == undefined || description == null || description == '') {
            api.toast({
                msg: "故障描述不允许为空！",
                duration: 3000
            });
            return
        }

        var imgs = document.getElementsByTagName('img');
        var names = [];
        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var srcStr = img.getAttribute('src');
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            if ("photo-add.png" != nameStr) {
                names[i] = nameStr;
            }
        }
        var picNames = JSON.parse(JSON.stringify(names)); 

        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/saveEquipmentFault";
        var data = {
            values: {
                equipCode: equipCode,
                description: description,
                voice: voice,
                isStop: isStop,
                location: location,
                happen: happen,
                bxPerson: bxPerson,
                mobile: mobile,
                urgent: urgent,
                picNames: picNames,

                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                //返回成功
                if (myobj.code == "0") {

                    api.toast({
                        msg: "保存成功",
                        duration: 3000
                    });
                    equipId = '';
                    personCode = '';

                    $("#equipCode").val("");
                    $("#description").val("");
                    $("#voice").val("");
                    $("#isStop").val("");
                    $("#location").val("");
                    $("#happen").val("");
                    // $("#bxPerson").val("");
                    // $("#mobile").val("");
                    $("#urgent").val("");
                    var liElements = document.querySelectorAll('#test'); // 查找所有具有id为'test'的li元素

                    // 遍历所有找到的li元素，并从其父元素中移除它们
                    liElements.forEach(function (liElement) {
                        liElement.parentNode.removeChild(liElement);
                    });
                    crateDate()
                    //失败，存在没有订单数据
                } else if (myobj.code == "1") {

                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }
    //扫描
    function doScan() {
        var moduleScanner = api.require('moduleScanner');
        var params = {
            top: 150, //扫描窗口的上边距
            width: 250, //扫描窗口的宽
            height: 250, //扫描窗口的高
            useColor: false, //是否使用自己设定的颜色(startColor和endColor),
            //如果不使用设定的颜色就使用默认的那张网格图
            startColor: '#0F08C8FF', //渐变起始颜色
            endColor: '#7F08C8FF', //渐变结束颜色
            animTime: 2200, //扫描动画时间,单位为毫秒
        };
        moduleScanner.toScannerActivityForResult(params, function (ret, err) {

            //赋值
            $("#" + idSelector).val(ret);

        });
    }

    //刀具序列号回车事件
    $("#equipCode").on('keypress', function (e) {
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {
            $("#equipCode").val(sm);

        }
    });

    function toNewPage() {
        var locationName = $("#locationName").val();
        var areaName = $("#areaName").val();
        var geographiclocation = $("#geographiclocation").val();
        api.openWin({
            name: 'emEquipmentList',
            url: 'emEquipmentList.html',
            pageParam: {
                name: "emEquipmentFaultLb",
            }
        });
    }

    function toNewPage2() {
        var locationName = $("#locationName").val();
        var areaName = $("#areaName").val();
        var geographiclocation = $("#geographiclocation").val();
        api.openWin({
            name: 'emEquipmentKnowledgeList',
            url: 'emEquipmentKnowledgeList.html',
            pageParam: {
                name: "emEquipmentFaultLb",
            }
        });
    }

    //选择带回回调函数
    function setEquip(sysid, code, name, locationName, areaName, zcwz) {
        equipId = sysid;
        $("#equipCode").val(code);
        $("#equipName").val(name);
        $("#locationName").val(locationName);
        $("#areaName").val(areaName);
        $("#geographiclocation").val(zcwz);
    }

    //选择带回回调函数
    function setEquip2(code, name, description) {
        $("#equipCode").val(code);
        $("#equipName").val(name);
        $("#description").val(description);
    }

    function imgClick() {
        // 获取图片宽高
        var normalW = $("#addpic img").width();
        api.actionSheet({
            title: '选择图片来源',
            buttons: ['照相机', '浏览相册']
        }, function (ret, err) {
            var index = ret.buttonIndex;
            switch (index) {
                // 拍照
                case 1:
                    // 打开拍照
                    api.getPicture({
                        sourceType: "camera",
                        encodingType: "jpg",
                        destinationType: "url",
                        mediaValue: "pic",
                        quality: 50,
                        saveToPhotoAlbum: true
                    }, function (ret, err) {
                        if (ret && ret.data) {
                            // 拍照返回的本地路径
                            var returnUrl = ret.data;
                            // 图片压缩
                            imgCompress(returnUrl, 0.5, 0.5, getExt(returnUrl), function (compressImg) {
                                var showImgHtml = "<li id='test' class='aui-list-view-cell aui-img aui-col-xs-4  aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                    "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                // 追加图片
                                $("#addpic").before(showImgHtml);
                                // ########################################  绑定长按事件 ########################
                                addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                //上传图片
                                uploadFile(compressImg);
                            });
                        } else {
                            api.toast({
                                msg: '没有选择，或者选择出错'
                            });
                        }
                    });
                    break;
                // 打开图片选择器
                case 2:
                    uiMediaScanner.open({
                        type: 'picture',
                        column: 4,
                        classify: true,
                        max: 5,
                        sort: {
                            key: 'time',
                            order: 'desc'
                        },
                        texts: {
                            stateText: '已选*项',
                            cancelText: '取消',
                            finishText: '完成'
                        },
                        styles: {
                            bg: '#fff',
                            mark: {
                                icon: '',
                                position: 'bottom_left',
                                size: 20
                            },
                            nav: {
                                bg: '#b23e4b',
                                stateColor: '#fff',
                                stateSize: 18,
                                cancelBg: 'rgba(0,0,0,0)',
                                cancelColor: '#fff',
                                cancelSize: 18,
                                finishBg: 'rgba(0,0,0,0)',
                                finishColor: '#fff',
                                finishSize: 18
                            }
                        }
                    }, function (ret) {
                        if (ret) {
                            if (ret.list) {
                                for (var i = 0; i < ret.list.length; i++) {
                                    console.log(i)
                                    var selectImg = ret.list[i];
                                    // 获取图片的路径
                                    var selectimgPath = selectImg.path;
                                    var selectimgThumbPath = selectImg.thumbPath;
                                    // 图片压缩
                                    imgCompress(selectimgPath, 0.5, 0.5, selectImg.suffix, function (compressImg) {
                                        var showImgHtml = "<li id='test' class='aui-list-view-cell aui-img aui-col-xs-4 aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;'  onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                            "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                        // 追加图片
                                        $("#addpic").before(showImgHtml);
                                        // ########################################  绑定长按事件 ########################
                                        addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                        // ################### 上传图片 #########################
                                        uploadFile(compressImg);
                                    });
                                }
                            }
                        }
                    });
                    break;
            }
        });
    }

    // 图片压缩
    // imgsrc：源图片的路径
    // quality：图片压缩质量，一般建议0.5
    // scale：图片压缩比例，也是建议0.5
    // ext：源图片拓展名
    // callback：转换成功之后回调函数
    function imgCompress(imgsrc, quality, scale, ext, callback) {
        // 压缩文件的保存目录
        var savePath = api.cacheDir + "/" + getNowFormatDate() + "/";
        // 压缩文件生成的随机文件名称
        var savename = NewGuid() + "." + ext;
        imageFilter.compress({
            img: imgsrc,
            quality: quality,
            scale: quality,
            save: {
                album: false,
                imgPath: savePath,
                imgName: savename
            }
        }, function (ret, err) {
            if (ret) {
                callback(savePath + savename);
            } else {
                console.log((JSON.stringify(err)));
            }
        });
    }

    // 打开图片浏览
    // imgs：需要预览的图片集合
    function openImageBrowser(imgs) {
        imageBrowser.openImages({
            imageUrls: imgs,
            showList: false,
            activeIndex: 0
        });
    }

    // 获取当前的时间，拼接成2015-11-09这样的格式，主要用于对图片进行时间分类
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate
        return currentdate;
    }

    // 获取文件拓展名
    function getExt(fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }

    // 生成guid,主要用于生成随机文件名
    function NewGuid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }

        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    // 添加长按方法
    function addPress(obj, index) {
        // 获取目前长按的对象
        var hammertime = new Hammer(obj[0]);
        // 绑定长按对象
        hammertime.on("press", function (e) {
            api.confirm({
                title: '温馨提示',
                msg: '您确定要删除该图片吗？',
                buttons: ['确定', '取消']
            }, function (ret, err) {
                if (ret.buttonIndex == 1) {
                    // 移除自己
                    $(obj).remove();
                    api.toast({
                        msg: '删除成功！'
                    });
                }
            });
        });
    }
  // 为图片添加点击预览功能,排除添加按钮
  function lookImg(compressImg) {
        // 定义一个数组，存储需要预览的图片
        var browerImgs = [];
        // 调用图片预览函数
        browerImgs.push(compressImg);
        openImageBrowser(browerImgs);
    }

    // 上传图片
    // url：上传的url地址
    // data：上传的文件
    // callback：上传成功返回地址
    function uploadFile(data) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/uploadPhotosAPP";
        var data = {
            values: {
                un: un
            },
            files: {
                file: data
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == "0") {
                    console.log("上传成功");
                } else if (myobj.code == "1") {
                    alert("上传失败");
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    //返回按钮
    function closeWin() {
        api.closeWin({});
    }
</script>

</html>